package com.portal.portal;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.gaeig.base.ApplicationInjector;
import com.portal.container.PortletContainer;
import com.portal.container.PortletContainerImpl;
import com.portal.portal.config.DriverConfigurationServiceFacade;
import com.portal.util.constants.ServletAttributeKeys;
import com.portal.util.exception.PortletContainerException;

public class PortalStartupListener implements ServletContextListener {

  private static final String PORTLET_NAME = "jojoPortlet";

  public void contextDestroyed(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    this.destroyContainer(context);
  }

  public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    initPortalDriverConfiguation(context);
    initPortletContainer(context);
  }

  private void initPortalDriverConfiguation(ServletContext servletContext) {
    DriverConfigurationServiceFacade.getInstance().init(servletContext);
  }

  private void initPortletContainer(ServletContext ctx) {
    PortletContainer container = new PortletContainerImpl(PORTLET_NAME, ApplicationInjector.getInjector().getInstance(PortalDriverService.class));
    try {
      container.init();
    } catch (PortletContainerException ex) {
      ex.printStackTrace();
    }
    ctx.setAttribute(ServletAttributeKeys.PORTLET_CONTAINER, container);
  }

  private void destroyContainer(ServletContext servletContext) {
    PortletContainer container = (PortletContainer) servletContext.getAttribute(ServletAttributeKeys.PORTLET_CONTAINER);
    if (container != null) {
      try {
        container.destroy();
      } catch (PortletContainerException ex) {
        ex.printStackTrace();
      } finally {
        servletContext.removeAttribute(ServletAttributeKeys.PORTLET_CONTAINER);
      }
    }
  }
}
